﻿using Aspose.Pdf;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.IdentityModel.Tokens;
using NaturalNote.Core;
using System.Threading;
using XxSystem.FileManager.core;

namespace XxSystem.FileManager.Controllers
{
    
    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {        
        string rootPath = "Y:\\books\\";
        readonly PhyFileService fileService;
        public FileController()
        {
            fileService = new PhyFileService("D盘", rootPath);
        }
        [HttpGet("list/{path?}")]
        public List<XFileInfo> GetDirs([FromRoute] string path = "")
        {         
           var dir = Base64UrlEncoder.Decode(path);
           var rs = fileService.GetList(dir).ToList();
            foreach (var r in rs) 
            {
                if (r.IsDir) {
                    continue;
                }
                if (r.Ext == "pdf" || r.Ext == "epub") 
                {
                    var up = HashUtil.Md5(Base64UrlEncoder.Encode(r.FullName));
                    r.Cover = $"http://localhost:5168/api/file/cover/{up}.jpg";
                    if (r.Ext == "pdf") 
                    {
                        // ConvertToTask.add(Base64UrlEncoder.Encode(r.FullName));
                    }
                }
            }
           return rs;
        }
       
        [HttpPost("upload")]
        public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files, string dir)
        {
            var files1 = Request.Form.Files;
            if (!string.IsNullOrWhiteSpace(dir))
            {
                //dir = CryptUtil.AesDecrypt(dir);
            }
            long size = files.Sum(f => f.Length);

            foreach (var formFile in files)
            {
                if (formFile!=null && formFile.Length > 0)
                {
                    var path = dir + "/" + formFile.FileName;                    
                    await fileService.Write(path, formFile.OpenReadStream());
                }
            }

            // Process uploaded files
            // Don't rely on or trust the FileName property without validation.

            return Ok(new { count = files.Count, size });
        }

        /// <summary>
        /// 文件流的方式输出
        /// </summary>
        /// <returns></returns>
        [HttpGet("download")]
        public IActionResult DownLoad(string file)
        {            
            if (!string.IsNullOrWhiteSpace(file))
            {
                //file = CryptUtil.AesDecrypt(file);
            }
            var fileInfo = fileService.Read(file);
            return File(fileInfo.DataStream, fileInfo.ContentType, fileInfo.FileName);
        }

        [HttpGet("cover/{path}.jpg")]
        public IActionResult Cover([FromRoute] string path) 
        {
            var truePath = $"H:\\obj_file_cover\\{path.Substring(0, 2)}\\{path.Substring(2, 4)}\\{path.Substring(6)}_80_100.jpg";
            if (!System.IO.File.Exists(truePath)) 
            {
                return NotFound();
            }

            var st = System.IO.File.OpenRead(truePath);
            return File(st, "image/jpeg", path + ".jpg");
        }

        [HttpGet("savecover")]
        public IActionResult SaveCover(string path) 
        {
            var dir = Base64UrlEncoder.Decode(path);
            var pdfPath = Path.Combine(rootPath, dir);
            // load PDF with an instance of Document                        
        
            var md5Path = HashUtil.Md5(Base64UrlEncoder.Encode(dir));
            var truePath = $"H:\\obj_file_cover\\{md5Path.Substring(0, 2)}\\{md5Path.Substring(2, 4)}";
            if (!Directory.Exists(truePath)) 
            { 
                Directory.CreateDirectory(truePath);
            }
            // convert a particular page and save the image in EMF format
            var orgJpgPath = $"{truePath}\\{md5Path.Substring(6)}.jpg";
            if (!System.IO.File.Exists(orgJpgPath)) {
                using var document = new Document(pdfPath);
                // create an object of EmfDevice
                var renderer = new Aspose.Pdf.Devices.JpegDevice();
                renderer.Process(document.Pages[1], orgJpgPath);
            }
            var orgJpgNewPath = $"{truePath}\\{md5Path.Substring(6)}_80_100.jpg";

            if (!System.IO.File.Exists(orgJpgNewPath))
            {
                ImgCovert.SaveNewSize(orgJpgPath, 80, 100, orgJpgNewPath);
            }
        
            return Ok();
        }

        
      

        [HttpPost("rename")]
        public IActionResult ReName([FromBody]ReNameRequest request)
        {
            var source = request.Dir + '/' + request.OldName;
            var target = request.Dir + '/' + request.NewName;
            fileService.Move(source, target);
            return Ok(request);
        }

        [HttpPost("move")]
        public IActionResult Move([FromBody] MoveRequest request)
        {
            fileService.Move(request.Source, request.Target);
            return Ok(request);
        }

        [HttpPost("move_dir")]
        public IActionResult MoveDir([FromBody] MoveRequest request)
        {
            fileService.MoveDir(request.Source, request.Target);
            return Ok(request);
        }

        [HttpPost("delete")]
        public IActionResult Delete([FromBody] List<string> files)
        {
            foreach (var item in files)
            {
                fileService.Delete(item);
            }
            return Ok(true);
        }

        [HttpDelete("delete_dir")]
        public IActionResult DeleteDir(string dir)
        {
            fileService.RmDir(dir);
            return Ok(true);
        }
    }
}
